package com.red.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.red.dao.User;
import com.red.mapper.UserMapper;
import com.red.service.UserService;
import com.red.connetcion.Result;
import com.red.connetcion.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.Objects;

public class UserServiceImpl implements UserService {
    private static final SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtil.getSqlSessionFactory();

    @Override
    public Result login(String username, String password) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.login(username, password);
        if (Objects.isNull(user)){
            return Result.fail("没有该用户");
        }
        User userWithOutPassword = BeanUtil.copyProperties(user, User.class, "password");

        return Result.ok(userWithOutPassword,"登陆成功");

    }

    @Override
    public Result register(User user) {
//        参数为true开启自动提交
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        try {
            userMapper.register(user);
        } catch (Exception e) {
            return Result.fail("用户名重复");
        }
//        sqlSession.commit();
        return Result.ok("注册成功");
    }
}
